import java.net.*;
import java.io.*;
import java.util.*;
import au.edu.uow.csci213quiz.*;

public class Server{
	

	
	private ServerSocket serverSocket;
	private Socket clientSocket;
	private int port;
	//private List<Question> questions = QuestionBuilder.buildQuestions();
	
	//constructor
	Server(){
		serverSocket = null;
		clientSocket=null;
		port = 40214;
		setPort(port);
		startServer();
	}
	
	Server(int port){
		serverSocket = null;
		clientSocket=null;
		this.port = port;
		setPort(port);
		startServer();
	}
	
	
	public void setPort(int port){
		this.port = port;
	}
		
	public int getPort(){
		return port;
	}

	public void shutdownServer(){
		try{
			serverSocket.close();
			clientSocket.close();
		}
		catch(IOException e){
			System.err.println("Error closing socket at port: "+getPort());
			System.exit(1);
		}
	}
	
	
	public void startServer(){

			
		try{
			serverSocket = new ServerSocket(port);
		}
		catch (IOException e){
			System.err.println("can't listen on port: "+getPort());
			System.exit(1);
		}
		
		System.out.println("JavaQuizServer listening at: "+getPort());
		//Collections.shuffle(questions);//make questions random
		int noConnections=0;
		while(noConnections<=2){
			
			//put last elemet first, and delete last elemet
			//this makes sure each thread has different question
			//questions.add(0,questions.get(questions.size()-1));
			//questions.remove(questions.size()-1);
			clientSocket = null;
			try{
				clientSocket = serverSocket.accept();
				ClientHandler ch = new ClientHandler(clientSocket);
				Thread t = new Thread(ch);
				t.start();
				noConnections++;
			}
			catch (IOException e){
				System.err.println("Accept failed");
				System.exit(1);
			}
	
		}
		
	}
		
	
	public static void main(String[] args){
		
		if(args.length<1){
			Server aServer = new Server();
		}
		else{
			Server aServer = new Server(Integer.parseInt(args[0]));
			
		}
		
        
	}
}


